package com.yy.tech.data.logger.filter;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.PropertyWriter;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.std.MapProperty;
import com.yy.tech.data.coder.encode.Encoder;
import com.yy.tech.data.logger.context.SecretRuleManager;

/**
 * @author yy
 * @date 2022/5/13
 * @description: TODO
 */
public class MapperPropertyFilter extends SimpleBeanPropertyFilter {

    @Override
    protected boolean include(final BeanPropertyWriter writer) {
        return SecretRuleManager.getManager().include(writer.getName())&&super.include(writer);
    }

    @Override
    protected boolean include(final PropertyWriter writer) {
        return SecretRuleManager.getManager().include(writer.getName())&&super.include(writer);
    }

    @Override
    public void serializeAsField(final Object pojo, final JsonGenerator jgen, final SerializerProvider provider, final PropertyWriter writer) throws Exception {
        String name = writer.getName();
        if (SecretRuleManager.getManager().match(name)){
            Encoder encoder = SecretRuleManager.getManager().findEncoder();
            if (null != encoder){
                if (writer instanceof MapProperty){
                    ((MapProperty) writer).setValue(encoder.convert(((MapProperty) writer).getValue()));
                }
            }
        }
        super.serializeAsField(pojo, jgen, provider, writer);
    }
}
